package demo.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import demo.entity.Student;
import demo.mappers.StudentRowMapper;

import java.util.List;

@Service
public class StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Student queryStudentById(int id) {
        String sql = "SELECT * FROM student WHERE id=? ";
        Student student = jdbcTemplate.queryForObject(sql, new StudentRowMapper(), id);
        return student;
    }


    public List<Student> queryAllStudents() {
        String sql = "SELECT * FROM student ORDER BY id";
        List<Student> studentList = jdbcTemplate.query(sql, new StudentRowMapper());
        return studentList;
    }

    public Student insertStudent(Student student) {
        String sql = "INSERT INTO student (id,name,student_number) VALUES(?, ?, ?)";
        jdbcTemplate.update(sql, null, student.getName(), student.getStudentNumber());
        String sql2 = "SELECT * FROM student WHERE student_number=? ";
        Student student2 = jdbcTemplate.queryForObject(sql2, new StudentRowMapper(), student.getStudentNumber());
        return student2;
    }

    public Student updateStudentById(int id,Student student){
        String sql = "UPDATE student set name=? , student_number =? WHERE id=?";
        jdbcTemplate.update(sql, student.getName(),student.getStudentNumber(),id);
        return queryStudentById(id);
    }

    public void deleteStudentById(int id) {
        String sql = "DELETE FROM student WHERE id=?";
        jdbcTemplate.update(sql, id);
    }
}
